package com.gsj.system.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.IPUtil;
import com.gsj.common.pojo.Payload;
import com.gsj.common.pojo.R;
import com.gsj.common.utils.JwtUtils;
import com.gsj.system.eneity.Log;
import com.gsj.system.eneity.User;
import com.gsj.system.service.OperationLogService;
import com.gsj.system.utils.WebUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Aspect
@Component
@RestControllerAdvice  //控制层异常处理类
public class OperLogAspect {
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    Log operlog = new Log();
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e){
        e.printStackTrace();//开发看的
        operationLogService.insert(operlog);

        return R.error();

    }

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.gsj.system.config.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.gsj.system.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);


        try {
//            operlog.setOperId(UuidUtil.get32UUID()); // 主键ID

            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String title = opLog.title();
                String operatorType = opLog.operatorType();
                String businessType = opLog.business_type();
                operlog.setTitle(title);
                operlog.setBusinessType(Integer.parseInt(businessType));
                operlog.setOperatorType(Integer.parseInt(operatorType));
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            operlog.setMethod(methodName);
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            String remoteAddr = request.getRemoteAddr();
            String a = "127.0.0.1";
            if(remoteAddr.equals(a)){
                operlog.setOperLocation("内网IP");
            }else {
                operlog.setOperLocation("外网IP");
            }
            // 请求URI
            operlog.setOperUrl(request.getRequestURI());
            // IP地址
            operlog.setOperIp(remoteAddr);
            // 请求参数
            operlog.setOperParam(params);
            // 创建时间
            operlog.setOperTime(new Date());
            String token = request.getHeader("token");
            Payload<User> infoFromToken = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
            User userInfo = infoFromToken.getUserInfo();
            String status = userInfo.getStatus();
            String userName = userInfo.getUserName();
            String DeptId = Integer.toString(userInfo.getDeptId());
            // 部门
            operlog.setDeptName(DeptId);
//             状态
            operlog.setStatus(Integer.parseInt(status));
            // 操作人
            operlog.setOperName(userName);

            System.out.println(operlog);
            operationLogService.insert(operlog);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);


        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            operlog.setOperParam(params); // 请求参数
            operlog.setMethod(methodName); // 请求方法名
            operlog.setErrorMsg(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
            String remoteAddr = request.getRemoteAddr();
            String a = "127.0.0.1";
            if(remoteAddr.equals(a)){
                operlog.setOperLocation("内网IP");
            }else {
                operlog.setOperLocation("外网IP");
            }
            // 请求URI
            operlog.setOperUrl(request.getRequestURI());
            // IP地址
            operlog.setOperIp(remoteAddr);
            // 请求参数
            operlog.setOperParam(params);
            // 创建时间
            operlog.setOperTime(new Date());
            String token = request.getHeader("token");
            Payload<User> infoFromToken = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
            User userInfo = infoFromToken.getUserInfo();
            String status = userInfo.getStatus();
            String userName = userInfo.getUserName();
            String DeptId = Integer.toString(userInfo.getDeptId());
            // 部门
            operlog.setDeptName(DeptId);
//             状态
            operlog.setStatus(Integer.parseInt(status));
            // 操作人
            operlog.setOperName(userName);

            System.out.println(operlog);



        } catch (Exception e2) {
            e2.printStackTrace();

        }

    }


    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }
    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

}